package com.micro.frog.rbac.controller;

import com.micro.frog.common.base.PageRes;
import com.micro.frog.common.base.Result;
import com.micro.frog.common.utils.BeanCopyUtil;
import com.micro.frog.rbac.dto.UserDTO;
import com.micro.frog.rbac.dto.UserDetail;
import com.micro.frog.rbac.entity.UserDO;
import com.micro.frog.rbac.service.UserService;
import com.micro.frog.rbac.util.SubjectUtil;
import com.micro.frog.rbac.vo.UserVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author :  ljh
 * @date : 2018/4/11
 **/
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/rbac/user")
public class UserController {

    private final UserService userService;

    @PostMapping(value = "/list")
    public Result list(@RequestBody UserDTO req) {
        List<UserDO> userList = userService.queryList(BeanCopyUtil.copy(req, UserDO.class));
        List<UserVO> voList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(userList)) {
            voList = BeanCopyUtil.copyList(userList, UserVO.class);
        }
        return Result.success(voList);
    }

    @PostMapping(value = "/page")
    public Result<PageRes<UserDO>> page(@RequestBody UserDTO req) {
        UserDO userDo = new UserDO();
        BeanCopyUtil.copy(req, userDo);
        return userService.queryPage(userDo, req.getPageNum(), req.getPageSize());
    }

    @PostMapping("/add")
    public Result add(UserVO req) {
        return userService.add(req);
    }

    @PostMapping("/delete")
    public Result delete(Long id) {
        boolean flag = userService.delete(id);
        return flag ? Result.success("删除成功") : Result.error("删除失败");
    }

    @PostMapping("/update")
    public Result update(UserVO req) {
        return userService.update(req);
    }

    @PostMapping("/updateStatus")
    public Result update(Long id, Integer status, HttpServletRequest request) {
        final Date current = new Date();
        UserDetail userDetail = SubjectUtil.getUser(request);
        UserDO user = new UserDO();
        user.setId(id);
        user.setStatus(status);
        user.setUpdatedBy(userDetail.getUserName());
        user.setUpdatedTime(current);
        return userService.updateStatus(user);
    }
}
